import { HttpClient } from '@angular/common/http';
import { Component, Input, Output, EventEmitter, ViewChild, TemplateRef, OnInit, HostBinding } from '@angular/core';

@Component({
    selector: 'app-preset-template-selector',
    templateUrl: './preset-template-selector.component.html',
    styleUrls: ['./preset-template-selector.component.css']
})
export class PresetTemplateSelectorComponent implements OnInit {

    @Input() templateUri;

    @Input() defaultSelectedTemplateId;

    @Output() cancel = new EventEmitter<any>();

    @Output() submit = new EventEmitter<any>();

    @HostBinding('class')
    class = 'd-flex f-utils-fill-flex-column h-100';

    /**
     * 可选的模板列表
     */
    presetTplList: any[];

    /**
     * 选中的模板
     */
    selectedTpl: any;

    showPreview = false;

    constructor(private http: HttpClient) {
    }

    ngOnInit() {
        this.getTemplate();
    }

    getTemplate() {
        const self = this;
        this.http.get<any[]>(this.templateUri).subscribe(data => {
            self.presetTplList = data || [];
            if (data.length) {
                const defaultSelectedTemplate = self.presetTplList.find(template => template.id === self.defaultSelectedTemplateId);
                if (defaultSelectedTemplate) {
                    self.selectedTpl = defaultSelectedTemplate;
                } else {
                    self.selectedTpl = self.presetTplList[0];
                }
            }
        });
    }

    changeTpl(tplId: string) {
        this.selectedTpl = this.presetTplList.find(t => t.id === tplId);
    }

    clickCancel() {
        this.cancel.emit();
    }

    clickConfirm() {
        this.submit.emit({
            id: this.selectedTpl.id,
            html: this.selectedTpl.templateHtml,
            presetsTemplateFragements: this.selectedTpl.presetsTemplateFragements,
            presetFields: this.selectedTpl.presetFields,
            customClass: this.selectedTpl.customClass,
            toolbarButtonClass: this.selectedTpl.toolbarButtonClass,
            toolbarButtonFragement: this.selectedTpl.toolbarButtonFragement,
            toolbarButtonIcons: this.selectedTpl.toolbarButtonIcons,
            toolbarFragement: this.selectedTpl.toolbarFragement,
            toolbarType: this.selectedTpl.toolbarType,
            toolbarWrapperFragement: this.selectedTpl.toolbarWrapperFragement
        });
    }

    showPreviewImage() {
        this.showPreview = true;
    }

    hidePreviewImage() {
        this.showPreview = false;
    }
}
